// FilesplitDlg.cpp : implementation file
//   Copyright(C) Lars Nordvall, 1998 - 2013
//

#include "stdafx.h"
#include "Filesplit.h"
#include "FilesplitDlg.h"
#include <cctype>


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#ifndef __FOLDERDLG_H__
    #include "FolderDlg.h"
#endif

CString MakeName(CString ,int);
/////////////////////////////////////////////////////////////////////////////
// CFilesplitDlg dialog

CFilesplitDlg::CFilesplitDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CFilesplitDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CFilesplitDlg)
	m_FileToCreate = _T("");
	m_nFileSize = 0;
	m_nAntalToCreate = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CFilesplitDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFilesplitDlg)
	DDX_Control(pDX, IDC_PROGRESS, m_Progress);
	DDX_Control(pDX, IDC_CreateSize, m_SizeToCreate);
	DDX_Text(pDX, IDC_FileToSplit, m_FileToCreate);
	DDX_Text(pDX, IDC_DestinationFilder, m_DestinationFolder);
	DDX_Text(pDX, IDC_FileSize, m_nFileSize);
	DDX_Text(pDX, IDC_ANT_CREATE, m_nAntalToCreate);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CFilesplitDlg, CDialog)
	//{{AFX_MSG_MAP(CFilesplitDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_SELECT, OnSelect)
	ON_CBN_KILLFOCUS(IDC_CreateSize, OnKillfocusCreateSize)
	ON_CBN_CLOSEUP(IDC_CreateSize, OnCloseupCreateSize)
	ON_CBN_EDITCHANGE(IDC_CreateSize, OnEditchangeCreateSize)
	ON_BN_CLICKED(IDC_SPLIT, OnSplit)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_SELECT2, &CFilesplitDlg::OnBnClickedSelect2)
	ON_EN_KILLFOCUS(IDC_FileToSplit, &CFilesplitDlg::OnEnKillfocusFiletosplit)
	ON_EN_KILLFOCUS(IDC_DestinationFilder, &CFilesplitDlg::OnEnKillfocusDestinationfilder)
	ON_BN_CLICKED(IDC_SPLIT2, &CFilesplitDlg::OnBnClickedSplit2)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFilesplitDlg message handlers

BOOL CFilesplitDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	// TODO: Add extra initialization here
	m_SizeToCreate.SetCurSel(0);
	TCHAR path[MAX_PATH];
	//GetCurrentDirectory(MAX_PATH, NPath);
	GetTempPath(MAX_PATH, path ); 
	m_DestinationFolder = path;//_T("c:\\");
	m_SizeToCreate.SetCurSel(2);
	UpdateData(false);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CFilesplitDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CFilesplitDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CFilesplitDlg::OnSelect() 
{
	// TODO: Add your control notification handler code here
	static char BASED_CODE szFilter[] = "All Files (*.*)|*.*|Archive Files (*.zip;*.lha;*.arj)|*.zip;*.lha;*.arj||";
	CHAR my_documents[MAX_PATH];
	CString startPath;
    //HRESULT result = SHGetFolderPath(NULL, CSIDL_RECENT, NULL, SHGFP_TYPE_CURRENT, my_documents);
	HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents);
	DWORD ftyp = GetFileAttributesA(my_documents);
    if (!(ftyp & FILE_ATTRIBUTE_DIRECTORY))
	{
		CString t(my_documents);
		int pos = t.Find('\\');
		startPath = t.Mid(0,pos);
	}
	else
	{
		startPath = my_documents;
	}
	if (startPath.Right(1) != '\\')
	{
		startPath.AppendChar('\\');
	}
	//HRESULT result = SHGetFolderLocation(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents);
	CFileDialog filedialog(TRUE,NULL,startPath,OFN_HIDEREADONLY,szFilter,this);
	
	if(IDOK == filedialog.DoModal())
	{
		m_FileToCreate = filedialog.GetPathName();
		CFile file(m_FileToCreate,CFile::modeRead);
		m_nFileSize = file.GetLength();
		file.Close( );
		Count();
		UpdateData(FALSE);
	}
}

void CFilesplitDlg::OnKillfocusCreateSize() 
{
	Count();
}

void CFilesplitDlg::OnCloseupCreateSize() 
{
	PostMessage(WM_SETFOCUS,0,0 );
}



void CFilesplitDlg::OnEditchangeCreateSize() 
{
	Count();
}

void CFilesplitDlg::Count(void) 
{
	char buf[256];
	char *ptr;

	m_SizeToCreate.GetWindowText(buf,256);

	m_nSizeToCreate=strtoul( buf,&ptr,10);
	CString t(ptr);
	if (t.Find("KB") > -1)
	{
		m_nSizeToCreate = m_nSizeToCreate *1024;
	}
	else if (t.Find("MB") > -1)
	{
		m_nSizeToCreate = m_nSizeToCreate *1024*1024;
	}
	else if (t.Find("GB") > -1 )
	{
		m_nSizeToCreate = m_nSizeToCreate *1024*1024*1024;
	}

	if (m_nSizeToCreate!=0)
		if (m_nFileSize % m_nSizeToCreate==0)
			m_nAntalToCreate = m_nFileSize / m_nSizeToCreate;
		else
			m_nAntalToCreate = (m_nFileSize / m_nSizeToCreate) + 1;
	else
		m_nAntalToCreate=0;
	UpdateData(FALSE);
}

void CFilesplitDlg::OnSplit() 
{
	CFile	Source;
	CFile	Dest;
	CString	destname;
	CString destFile;
	unsigned int	antalgjorda;
	char *buffer;

	if (m_nAntalToCreate==0)
	{
		MessageBox("Select file first");
	}
	else if (m_FileToCreate.GetLength() < 3)
	{
		MessageBox("Select file first");
	}
	else if (m_DestinationFolder.GetLength() < 3)
	{
		MessageBox("Specify destination folder");
	}
	else
	{
		m_Progress.SetRange( 0, (m_nAntalToCreate+1) * 10 );
		ULONGLONG bufferSize = m_nSizeToCreate < 256*1024*1024 ? m_nSizeToCreate : 256*1024*1024;
		buffer=new char[bufferSize];
		Source.Open(m_FileToCreate, CFile::modeRead | CFile::shareDenyWrite,NULL );
		for (antalgjorda=0;antalgjorda<m_nAntalToCreate;antalgjorda++)
		{
			m_Progress.StepIt();
			destFile = MakeName(Source.GetFileTitle(),antalgjorda);
			destname = m_DestinationFolder;
			if (destname.Right(1) != '\\')
			{
				destname.AppendChar('\\');
			}
			destname.Append(destFile);
			Dest.Open(destname,CFile::modeCreate | CFile::modeWrite,NULL);
			for (ULONGLONG leftToWrite = m_nSizeToCreate; leftToWrite > 0; leftToWrite = leftToWrite-bufferSize)
			{
				Dest.Write(buffer,Source.Read(buffer,bufferSize));
			}
			Dest.Close();
		}
		delete buffer;
		Source.Close();
		m_Progress.StepIt();
		MessageBox("Split complete !");
		m_Progress.SetPos(0);
	}
}

CString MakeName(CString filename,int count)
{
	char	ext[5];
	filename=filename.Left(filename.Find('.'));
	ext[0]='.';
	ext[4]='\0';
	if (count<10)
	{
		ext[1]='0';
		ext[2]='0';
		itoa(count,ext+3,10);
	}
	if (count<100&&count>9)
	{
		ext[1]='0';
		itoa(count,ext+2,10);
	}
	if (count>99)
		itoa(count,ext+1,10);
	ext[4]='\0';
	filename+=ext;
	return filename;
}


void CFilesplitDlg::OnBnClickedSelect2()
{
	m_DestinationFolder = _T( "c:\\" ); // Just for sample    
    //CString m_strDisplayName.Empty();
    
    CFolderDialog dlg(  _T( "Dialog Title" ), m_DestinationFolder, this );
    if( dlg.DoModal() == IDOK  )
    {    
        m_DestinationFolder  = dlg.GetFolderPath();
        //m_strDisplayName = dlg.GetFolderDisplayName();
        // Use folder path and display name here ...
    }    
	
	UpdateData(FALSE);
}


void CFilesplitDlg::OnEnKillfocusFiletosplit()
{
	UpdateData(true);
}


void CFilesplitDlg::OnEnKillfocusDestinationfilder()
{
	UpdateData(true);
}


void CFilesplitDlg::OnBnClickedSplit2()
{
	MessageBox("use:\n c:>copy /B fileName* destinationFilename\nto merge files");
}
